package admin

import (
	"fmt"
	"mycms/global"
	"mycms/model/system"
	systemReq "mycms/model/system/request"
	systemRes "mycms/model/system/response"
	"mycms/service/common"
	"strconv"
)

//	角色列表
func GetRoleList(param systemReq.SearchRoleParams) (err error, list interface{}, total int64) {

	var roleList []system.Role
	var roleRes []systemRes.RoleListResponse

	db := global.DB.Model(&system.Role{})
	err = db.Count(&total).Error

	if err != nil {
		return err, roleList, total
	} else {
		if param.Name != "" {
			db = db.Where("name LIKE ?", "%"+param.Name+"%")
		}

		if param.Status != 0 {
			db = db.Where("status = ?", param.Status)
		}

		//	查询
		err = db.Scopes(common.Paginate(param.PageInfo)).Find(&roleList).Error

		//	有数据时，循环处理一下数据
		if len(roleList) > 0 {
			for _, v := range roleList {
				roleRes = append(roleRes, systemRes.RoleListResponse{
					Id:        v.ID,
					Name:      v.Name,
					Code:      v.Code,
					Remark:    v.Remark,
					Status:    v.Status,
					CreatedAt: v.CreatedAt.Format("2006-01-02 15:04:05"),
				})
			}

		}
	}

	return err, roleRes, total
}


//	角色详情
func GetRoleInfo(param systemReq.RoleInfoParams) (err error, role system.Role) {

	//e := global.DB.Model(&role).Association("RoleId").Error
	//
	//if e != nil{
	//	fmt.Printf(e.Error())
	//}

	err = global.DB.Where("id = ?", param.Id).Preload("RoleMenu").First(&role).Error
	//var role_menu system.RoleMenu
	//global.DB.Model(&role).Association("role_id").Find(&role_menu)
	fmt.Printf("%+v", role)
	return err, role
}

//	新增角色
func CreateRole(param systemReq.CreateRoleParams) (err error) {

	var role_menu system.RoleMenu
	role := &system.Role{
		Name: param.Name,
		Code: param.Code,
		Status: param.Status,
		Remark: param.Remark,
	}
	tx := global.DB.Begin()

	//	延时回调
	defer func() {
		if r := recover(); r != nil {
			//	事务回滚
			tx.Rollback()
		}
	}()

	//	事务开启失败时返回错误
	if err := tx.Error; err != nil {
		return err
	}

	err = tx.Create(role).Error

	if err == nil {

		//	TODO 更新关联表
		if err = tx.Where("role_id = ?", role.ID).Delete(&role_menu).Error; err != nil{
			tx.Rollback()
			return err
		}

		var createData []system.RoleMenu

		for _, v := range param.Menus{
			createData = append(createData, system.RoleMenu{
				RoleId: role.ID,
				MenuId: v,
			})
		}

		if len(createData) > 0{

			if err = tx.Create(&createData).Error; err != nil{
				tx.Rollback()
				return err
			}
		}

	}

	//	事务提交
	return tx.Commit().Error
}

//	编辑角色
func UpdateRole(param systemReq.UpdateRoleParams) (err error) {
	var role system.Role
	var role_menu system.RoleMenu

	tx := global.DB.Begin()

	//	延时回调
	defer func() {
		if r := recover(); r != nil {
			//	事务回滚
			tx.Rollback()
		}
	}()

	//	事务开启失败时返回错误
	if err := tx.Error; err != nil {
		return err
	}

	err = tx.Where("id = ?", param.Id).First(&role).Error

	if err == nil {
		//	更新角色
		if err = tx.Model(role).Where("id = ?", param.Id).Updates(&system.Role{
			Name: param.Name,
			Code: param.Code,
			Status: param.Status,
			Remark: param.Remark,
		}).Error; err != nil{
			tx.Rollback()
			return err
		}

		//	TODO 更新关联表
		if err = tx.Where("role_id = ?", param.Id).Delete(&role_menu).Error; err != nil{
			tx.Rollback()
			return err
		}

		var createData []system.RoleMenu

		for _, v := range param.Menus{
			createData = append(createData, system.RoleMenu{
				RoleId: param.Id,
				MenuId: v,
			})
		}

		if len(createData) > 0{
			if err = tx.Create(&createData).Error; err != nil{
				tx.Rollback()
				return err
			}
		}

		// 更新角色权限
		authorityId := int(param.Id)
		err := UpdateRoleRule(authorityId)
		if(err != nil){
			tx.Rollback()
			return err
		}

	}

	//	事务提交
	return tx.Commit().Error
}

//	删除角色
func DelRole(param systemReq.RoleDelParams) (err error) {
	var role system.Role
	err = global.DB.Where("id = ?", param.Id).Delete(&role).Error
	return err
}

//	更新角色权限
func UpdateRoleRule(role_id int) (err error) {
	//	查询角色对应所有菜单的API
	var api []system.Apis
	err = global.DB.Joins("JOIN gox_menu_apis ON gox_menu_apis.api_id = gox_apis.id").Joins("JOIN gox_role_menu ON gox_role_menu.menu_id = gox_menu_apis.menu_id").Where("gox_role_menu.role_id = ?", role_id).Group("gox_apis.id").Find(&api).Error

	if err != nil{
		return err
	}

	//	获取默认权限
	list := systemReq.DefaultCasbin()

	//	把角色的权限添加到列表
	if len(api) > 0{
		for _, val := range api{
			list = append(list, systemReq.CasbinInfo{
				Path: val.Path,
				Method: val.Method,
			})
		}
	}
	err = common.CasbinServiceApp.UpdateCasbin(strconv.Itoa(role_id), list)

	return err
}
